package com.shyfu.controllers;

import com.shyfu.Utils;
import com.shyfu.entities.Author;
import com.shyfu.entities.Book;
import com.shyfu.entities.User;
import com.shyfu.services.AuthorService;
import com.shyfu.services.BookService;
import com.shyfu.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Svitlana on 04-Apr-14.
 */
@Controller
@RequestMapping("/librry")
public class HomePageController {

    @Autowired
    private BookService bookService;
    @Autowired
    private AuthorService authorService;
    @Autowired
    private ControllerUtils controllerUtils;
    @Autowired
    private UserService userService;

    @RequestMapping("/ws/book/{id}")
    public
    @ResponseBody
    Book getBook(@PathVariable long id) {
        return controllerUtils.convertBook(id);
    }

    @RequestMapping("/ws/user/{id}")
    public
    @ResponseBody
    User getUser(@PathVariable long id) {
        return controllerUtils.convertUser(id);
    }

    @RequestMapping("/add/book")
    public String addBook(@RequestParam(value = "book_title") String title,
                          @RequestParam(value = "author") String author,
                          @RequestParam(value = "fname") String firstName,
                          @RequestParam(value = "lname") String lastName,
                          @RequestParam(value = "cover") MultipartFile coverFile,
                          @RequestParam("year") String year,
                          @RequestParam(value = "book") MultipartFile bookFile, HttpServletRequest request) throws ParseException {
        Date bookYear = new SimpleDateFormat("YYYY").parse(year);
        System.out.println("cover = " + coverFile.getOriginalFilename());
        System.out.println("book = " + bookFile.getOriginalFilename());
        String bookPath = request.getSession().getServletContext().getRealPath("resources/librry/books/files");
        File bFile = new File(bookPath + "/" + bookFile.getOriginalFilename());
        String coverPath = request.getSession().getServletContext().getRealPath("resources/librry/books/covers");
        System.out.println("bookPath = " + bookPath);
        System.out.println("coverPath = " + coverPath);
        File cFile = new File(coverPath + "/" + coverFile.getOriginalFilename());
        try {
            bookFile.transferTo(bFile);
            coverFile.transferTo(cFile);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("error copying files");
        }
        Author newAuthor = null;
        if (!firstName.isEmpty() && !lastName.isEmpty()) {
            newAuthor = new Author();
            newAuthor.setFirstName(firstName);
            newAuthor.setLastName(lastName);
            newAuthor.setBirthDate(new Timestamp(bookYear.getTime()));
            authorService.addAuthor(newAuthor);
        } else {
            newAuthor = authorService.getAuthor(Long.parseLong(author));
        }
        User user = controllerUtils.getUser(request);

        controllerUtils.createBook(title, coverFile.getOriginalFilename(), bookFile.getOriginalFilename(), bookYear, newAuthor, user);

        return "redirect:/librry";
    }

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView getHomePage(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("home");
        modelAndView.addObject("books", bookService.getAllBooks());
        modelAndView.addObject("authors", authorService.getAllAuthors());
        modelAndView.addObject("contextPath", Utils.getContextPath(request));
        modelAndView.addObject("user", controllerUtils.getUser(request));
        return modelAndView;
    }
}